<script setup>
import { ref } from 'vue'
import {
  memberPageQueryService,
  deleteMemberService,
  rechargeMemberBalanceService
} from '@/api/member.js'
import { updateUserStatusService } from '@/api/user.js'
import {
  Search,
  Refresh,
  Edit,
  Delete,
  DCaret,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import MemberEdit from './components/MemberEdit.vue'
import { useUserStore } from '@/stores'

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const memberList = ref([]) // 会员列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态
const balanceHoverStates = ref({}) // 存储每一行的余额悬停状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  name: null, // 会员姓名
  status: null, // 用户状态
  level: null // 会员等级
})

// 会员等级与el-tag类型映射
const memberLevelTagTypeMap = {
  普通: 'info',
  银卡: 'primary',
  金卡: 'warning',
  至尊: 'danger'
}
const getMemberLevelTagType = (level) => {
  return memberLevelTagTypeMap[level] || 'info'
}

// 基于params参数，获取会员列表
const getMemberList = async () => {
  loading.value = true
  const res = await memberPageQueryService(params.value)
  memberList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
  // 初始化悬停状态
  memberList.value.forEach((member) => {
    balanceHoverStates.value[member.id] = false
  })
}
getMemberList()

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getMemberList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getMemberList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getMemberList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getMemberList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    name: null,
    status: null,
    level: null
  }
  getMemberList()
}

const memberEditRef = ref()
// 新增逻辑
const handleAdd = () => {
  memberEditRef.value.open({})
}

// 编辑逻辑
const handleEdit = (row) => {
  memberEditRef.value.open(row)
}

// 删除逻辑
const handleDelete = async (row) => {
  await ElMessageBox.confirm('是否确认删除该会员？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteMemberService(row.id)
  ElNotification({
    title: '删除成功',
    type: 'success'
  })
  getMemberList()
}

// 修改用户状态
const handleStatusChange = async (row) => {
  try {
    await updateUserStatusService(row.status, row.userId)
    ElNotification({
      title: `${row.status}用户状态成功`,
      type: 'success'
    })
  } catch (error) {
    row.status = row.status === '启用' ? '禁用' : '启用'
  }
}

// 会员余额充值
const balanceRechargeDTO = ref({
  id: null,
  amount: 0
})
const visibleRechargeDialog = ref(false)
const handleMouseOver = (id) => {
  if (['管理员', '店长', '收银员'].includes(userRole)) {
    balanceHoverStates.value[id] = true
  }
}
const handleMouseLeave = (id) => {
  balanceHoverStates.value[id] = false
}
const handleClickBalanceRecharge = (row) => {
  balanceRechargeDTO.value = {
    id: row.id,
    amount: 0
  }
  visibleRechargeDialog.value = true
}
const handleCancelBalanceRecharge = () => {
  visibleRechargeDialog.value = false
}
const handleConfirmBalanceRecharge = async () => {
  await rechargeMemberBalanceService(balanceRechargeDTO.value.amount, balanceRechargeDTO.value.id)
  ElNotification({
    title: `会员余额充值成功`,
    type: 'success'
  })
  visibleRechargeDialog.value = false
  getMemberList()
}
</script>

<template>
  <page-container title="会员管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >新增会员</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="会员姓名:">
        <el-input v-model="params.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="用户状态:">
        <el-select v-model="params.status" style="width: 100px">
          <el-option label="禁用" value="禁用"></el-option>
          <el-option label="启用" value="启用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会员等级:">
        <el-select v-model="params.level" style="width: 100px">
          <el-option label="普通" value="普通"></el-option>
          <el-option label="银卡" value="银卡"></el-option>
          <el-option label="金卡" value="金卡"></el-option>
          <el-option label="至尊" value="至尊"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table class="tb" :data="memberList" v-loading="loading" :row-style="{ height: '50px' }">
      <el-table-column prop="id" label="会员ID" width="100">
        <template #header>
          <span>会员ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" width="100">
        <template #header>
          <span>用户ID</span>
          <el-icon @click="handleSort('user_id')">
            <component :is="getSortIcon('user_id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="avatarUrl" label="头像" width="100">
        <template #default="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.avatarUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="age" label="年龄" width="60" />
      <el-table-column prop="mobilePhone" label="移动电话" width="120" />
      <el-table-column prop="idNumber" label="身份证号码" width="180" />
      <el-table-column prop="email" label="电子邮箱" width="150" show-overflow-tooltip />
      <el-table-column prop="address" label="地址" width="150" show-overflow-tooltip />
      <el-table-column prop="status" label="用户状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-value="启用"
            inactive-value="禁用"
            active-text="启用"
            inactive-text="禁用"
            @click="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="level" label="会员等级" width="80">
        <template #default="{ row }">
          <el-tag :type="getMemberLevelTagType(row.level)">{{ row.level }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="points" label="会员积分" width="100" />
      <el-table-column prop="balance" label="账户余额" width="120">
        <template #default="{ row }">
          <div
            @mouseover="handleMouseOver(row.id)"
            @mouseleave="handleMouseLeave(row.id)"
            style="position: relative; display: inline-block"
          >
            <el-button
              v-if="['管理员', '店长', '收银员'].includes(userRole)"
              v-show="balanceHoverStates[row.id]"
              type="primary"
              size="small"
              plain
              @click="handleClickBalanceRecharge(row)"
              style="padding: 5px"
            >
              余额充值
            </el-button>
            <div v-show="!balanceHoverStates[row.id]">{{ (row.balance / 100).toFixed(2) }}元</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalServicesCount" label="服务总次数" width="100" />
      <el-table-column prop="lastServiceTime" label="上次服务时间" width="180">
        <template #header>
          <span>上次服务时间</span>
          <el-icon @click="handleSort('last_service_time')">
            <component :is="getSortIcon('last_service_time')" />
          </el-icon>
        </template>
        <template #default="{ row }">
          <div>{{ row.lastServiceTime ?? '---' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="上次登录时间" width="180">
        <template #default="{ row }">
          <div>{{ row.lastLoginTime ?? '---' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column
        v-if="['管理员', '店长'].includes(userRole)"
        label="操作"
        width="180"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            plain
            size="small"
            @click="handleEdit(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            plain
            size="small"
            @click="handleDelete(row)"
          ></el-button>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 抽屉 -->
  <member-edit ref="memberEditRef" @success="handleReset"></member-edit>
  <!-- 余额充值对话框 -->
  <el-dialog v-model="visibleRechargeDialog" title="会员余额充值" width="500">
    <el-form ref="formRef" label-width="auto">
      <el-form-item label="充值金额">
        <el-input
          v-model.number="balanceRechargeDTO.amount"
          type="number"
          placeholder="请输入充值金额"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelBalanceRecharge">取消</el-button>
        <el-button type="primary" @click="handleConfirmBalanceRecharge">充值</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
